package com.xuliugen.demo.multithread.treadlocal;

import java.util.HashMap;
import java.util.Map;

/**
 * 演示弱引用自己设置为Null的时候
 * Created by xuliugen on 2017/11/12.
 */
public class ThreadLocalWeakReferenceSetNullDemo {

    private static final int THREAD_LOOP_SIZE = 20;

    public static void main(String[] args) {

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ThreadLocal<String> threadLocalSetNull = new ThreadLocal<>();
        threadLocalSetNull.set("我是threadLocalSetNull");

        for (int i = 1; i <= THREAD_LOOP_SIZE; i++) {
            Map<Integer, String> map = new HashMap<>();
            map.put(i, "我是第" + i + "个ThreadLocal数据！");
            ThreadLocal<Map<Integer, String>> threadLocal = new ThreadLocal<>();
            threadLocal.set(map);
            threadLocal.get();
            if (i == 3) {
                threadLocalSetNull = null;
            }
            if (i == THREAD_LOOP_SIZE) {
                threadLocal.get();
            }

            System.out.println("第" + i + "次获取ThreadLocal中的数据");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
